home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 2 / Meeting Pearls Vol. II (1995)(GTI - Schatztruhe)[!].iso / Pearls / gfx / pbm / source / jpegV5.lha / jpegV5 / src / rdgif.c < prev    next >
C/C++ Source or Header  |  1994-12-23  |  22KB  |  672 lines

  1. /*
  2.  * rdgif.c
  3.  *
  4.  * Copyright (C) 1991-1994, Thomas G. Lane.
  5.  * This file is part of the Independent JPEG Group's software.
  6.  * For conditions of distribution and use, see the accompanying README file.
  7.  *
  8.  * This file contains routines to read input images in GIF format.
  9.  *
  10.  * These routines may need modification for non-Unix environments or
  11.  * specialized applications.  As they stand, they assume input from
  12.  * an ordinary stdio stream.  They further assume that reading begins
  13.  * at the start of the file; input_init may need work if the
  14.  * user interface has already read some data (e.g., to determine that
  15.  * the file is indeed GIF format).
  16.  */
  17.  
  18. /*
  19.  * This code is loosely based on giftoppm from the PBMPLUS distribution
  20.  * of Feb. 1991.  That file contains the following copyright notice:
  21.  * +-------------------------------------------------------------------+
  22.  * | Copyright 1990, David Koblas.                                     |
  23.  * |   Permission to use, copy, modify, and distribute this software   |
  24.  * |   and its documentation for any purpose and without fee is hereby |
  25.  * |   granted, provided that the above copyright notice appear in all |
  26.  * |   copies and that both that copyright notice and this permission  |
  27.  * |   notice appear in supporting documentation.  This software is    |
  28.  * |   provided "as is" without express or implied warranty.           |
  29.  * +-------------------------------------------------------------------+
  30.  *
  31.  * We are also required to state that
  32.  *    "The Graphics Interchange Format(c) is the Copyright property of
  33.  *    CompuServe Incorporated. GIF(sm) is a Service Mark property of
  34.  *    CompuServe Incorporated."
  35.  */
  36.  
  37. #include "cdjpeg.h"        /* Common decls for cjpeg/djpeg applications */
  38.  
  39. #ifdef GIF_SUPPORTED
  40.  
  41.  
  42. #define    MAXCOLORMAPSIZE    256    /* max # of colors in a GIF colormap */
  43. #define NUMCOLORS    3    /* # of colors */
  44. #define CM_RED        0    /* color component numbers */
  45. #define CM_GREEN    1
  46. #define CM_BLUE        2
  47.  
  48. #define    MAX_LZW_BITS    12    /* maximum LZW code size */
  49. #define LZW_TABLE_SIZE    (1<<MAX_LZW_BITS) /* # of possible LZW symbols */
  50.  
  51. /* Macros for extracting header data --- note we assume chars may be signed */
  52.  
  53. #define LM_to_uint(a,b)        ((((b)&0xFF) << 8) | ((a)&0xFF))
  54.  
  55. #define BitSet(byte, bit)    ((byte) & (bit))
  56. #define INTERLACE    0x40    /* mask for bit signifying interlaced image */
  57. #define COLORMAPFLAG    0x80    /* mask for bit signifying colormap presence */
  58.  
  59. #define    ReadOK(file,buffer,len)    (JFREAD(file,buffer,len) == ((size_t) (len)))
  60.  
  61. /* LZW decompression tables look like this:
  62.  *   symbol_head[K] = prefix symbol of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  63.  *   symbol_tail[K] = suffix byte   of any LZW symbol K (0..LZW_TABLE_SIZE-1)
  64.  * Note that entries 0..end_code of the above tables are not used,
  65.  * since those symbols represent raw bytes or special codes.
  66.  *
  67.  * The stack represents the not-yet-used expansion of the last LZW symbol.
  68.  * In the worst case, a symbol could expand to as many bytes as there are
  69.  * LZW symbols, so we allocate LZW_TABLE_SIZE bytes for the stack.
  70.  * (This is conservative since that number includes the raw-byte symbols.)
  71.  *
  72.  * The tables are allocated from FAR heap space since they would use up
  73.  * rather a lot of the near data space in a PC.
  74.  */
  75.  
  76.  
  77. /* Private version of data source object */
  78.  
  79. typedef struct {
  80.   struct cjpeg_source_struct pub; /* public fields */
  81.  
  82.   j_compress_ptr cinfo;        /* back link saves passing separate parm */
  83.  
  84.   JSAMPARRAY colormap;        /* GIF colormap (converted to my format) */
  85.  
  86.   /* State for GetCode and LZWReadByte */
  87.   char code_buf[256+4];        /* current input data block */
  88.   int last_byte;        /* # of bytes in code_buf */
  89.   int last_bit;            /* # of bits in code_buf */
  90.   int cur_bit;            /* next bit index to read */
  91.   boolean out_of_blocks;    /* TRUE if hit terminator data block */
  92.  
  93.   int input_code_size;        /* codesize given in GIF file */
  94.   int clear_code,end_code;    /* values for Clear and End codes */
  95.  
  96.   int code_size;        /* current actual code size */
  97.   int limit_code;        /* 2^code_size */
  98.   int max_code;            /* first unused code value */
  99.   boolean first_time;        /* flags first call to LZWReadByte */
  100.  
  101.   /* Private state for LZWReadByte */
  102.   int oldcode;            /* previous LZW symbol */
  103.   int firstcode;        /* first byte of oldcode's expansion */
  104.  
  105.   /* LZW symbol table and expansion stack */
  106.   UINT16 FAR *symbol_head;    /* => table of prefix symbols */
  107.   UINT8  FAR *symbol_tail;    /* => table of suffix bytes */
  108.   UINT8  FAR *symbol_stack;    /* => stack for symbol expansions */
  109.   UINT8  FAR *sp;        /* stack pointer */
  110.  
  111.   /* State for interlaced image processing */
  112.   boolean is_interlaced;    /* TRUE if have interlaced image */
  113.   jvirt_sarray_ptr interlaced_image; /* full image in interlaced order */
  114.   JDIMENSION cur_row_number;    /* need to know actual row number */
  115.   JDIMENSION pass2_offset;    /* # of pixel rows in pass 1 */
  116.   JDIMENSION pass3_offset;    /* # of pixel rows in passes 1&2 */
  117.   JDIMENSION pass4_offset;    /* # of pixel rows in passes 1,2,3 */
  118. } gif_source_struct;
  119.  
  120. typedef gif_source_struct * gif_source_ptr;
  121.  
  122.  
  123. /* Forward declarations */
  124. METHODDEF JDIMENSION get_pixel_rows
  125.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  126. METHODDEF JDIMENSION load_interlaced_image
  127.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  128. METHODDEF JDIMENSION get_interlaced_row
  129.     JPP((j_compress_ptr cinfo, cjpeg_source_ptr sinfo));
  130.  
  131.  
  132. LOCAL int
  133. ReadByte (gif_source_ptr sinfo)
  134. /* Read next byte from GIF file */
  135. {
  136.   register FILE * infile = sinfo->pub.input_file;
  137.   int c;
  138.  
  139.   if ((c = getc(infile)) == EOF)
  140.     ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  141.   return c;
  142. }
  143.  
  144.  
  145. LOCAL int
  146. GetDataBlock (gif_source_ptr sinfo, char *buf)
  147. /* Read a GIF data block, which has a leading count byte */
  148. /* A zero-length block marks the end of a data block sequence */
  149. {
  150.   int count;
  151.  
  152.   count = ReadByte(sinfo);
  153.   if (count > 0) {
  154.     if (! ReadOK(sinfo->pub.input_file, buf, count))
  155.       ERREXIT(sinfo->cinfo, JERR_INPUT_EOF);
  156.   }
  157.   return count;
  158. }
  159.  
  160.  
  161. LOCAL void
  162. SkipDataBlocks (gif_source_ptr sinfo)
  163. /* Skip a series of data blocks, until a block terminator is found */
  164. {
  165.   char buf[256];
  166.  
  167.   while (GetDataBlock(sinfo, buf) > 0)
  168.     /* skip */;
  169. }
  170.  
  171.  
  172. LOCAL void
  173. ReInitLZW (gif_source_ptr sinfo)
  174. /* (Re)initialize LZW state; shared code for startup and Clear processing */
  175. {
  176.   sinfo->code_size = sinfo->input_code_size + 1;
  177.   sinfo->limit_code = sinfo->clear_code << 1;    /* 2^code_size */
  178.   sinfo->max_code = sinfo->clear_code + 2;    /* first unused code value */
  179.   sinfo->sp = sinfo->symbol_stack;        /* init stack to empty */
  180. }
  181.  
  182.  
  183. LOCAL void
  184. InitLZWCode (gif_source_ptr sinfo)
  185. /* Initialize for a series of LZWReadByte (and hence GetCode) calls */
  186. {
  187.   /* GetCode initialization */
  188.   sinfo->last_byte = 2;        /* make safe to "recopy last two bytes" */
  189.   sinfo->last_bit = 0;        /* nothing in the buffer */
  190.   sinfo->cur_bit = 0;        /* force buffer load on first call */
  191.   sinfo->out_of_blocks = FALSE;
  192.  
  193.   /* LZWReadByte initialization: */
  194.   /* compute special code values (note that these do not change later) */
  195.   sinfo->clear_code = 1 << sinfo->input_code_size;
  196.   sinfo->end_code = sinfo->clear_code + 1;
  197.   sinfo->first_time = TRUE;
  198.   ReInitLZW(sinfo);
  199. }
  200.  
  201.  
  202. LOCAL int
  203. GetCode (gif_source_ptr sinfo)
  204. /* Fetch the next code_size bits from the GIF data */
  205. /* We assume code_size is less than 16 */
  206. {
  207.   register INT32 accum;
  208.   int offs, ret, count;
  209.  
  210.   while ( (sinfo->cur_bit + sinfo->code_size) > sinfo->last_bit) {
  211.     /* Time to reload the buffer */
  212.     if (sinfo->out_of_blocks) {
  213.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  214.       return sinfo->end_code;    /* fake something useful */
  215.     }
  216.     /* preserve last two bytes of what we have -- assume code_size <= 16 */
  217.     sinfo->code_buf[0] = sinfo->code_buf[sinfo->last_byte-2];
  218.     sinfo->code_buf[1] = sinfo->code_buf[sinfo->last_byte-1];
  219.     /* Load more bytes; set flag if we reach the terminator block */
  220.     if ((count = GetDataBlock(sinfo, &sinfo->code_buf[2])) == 0) {
  221.       sinfo->out_of_blocks = TRUE;
  222.       WARNMS(sinfo->cinfo, JWRN_GIF_NOMOREDATA);
  223.       return sinfo->end_code;    /* fake something useful */
  224.     }
  225.     /* Reset counters */
  226.     sinfo->cur_bit = (sinfo->cur_bit - sinfo->last_bit) + 16;
  227.     sinfo->last_byte = 2 + count;
  228.     sinfo->last_bit = sinfo->last_byte * 8;
  229.   }
  230.  
  231.   /* Form up next 24 bits in accum */
  232.   offs = sinfo->cur_bit >> 3;    /* byte containing cur_bit */
  233. #ifdef CHAR_IS_UNSIGNED
  234.   accum = sinfo->code_buf[offs+2];
  235.   accum <<= 8;
  236.   accum |= sinfo->code_buf[offs+1];
  237.   accum <<= 8;
  238.   accum |= sinfo->code_buf[offs];
  239. #else
  240.   accum = sinfo->code_buf[offs+2] & 0xFF;
  241.   accum <<= 8;
  242.   accum |= sinfo->code_buf[offs+1] & 0xFF;
  243.   accum <<= 8;
  244.   accum |= sinfo->code_buf[offs] & 0xFF;
  245. #endif
  246.  
  247.   /* Right-align cur_bit in accum, then mask off desired number of bits */
  248.   accum >>= (sinfo->cur_bit & 7);
  249.   ret = ((int) accum) & ((1 << sinfo->code_size) - 1);
  250.   
  251.   sinfo->cur_bit += sinfo->code_size;
  252.   return ret;
  253. }
  254.  
  255.  
  256. LOCAL int
  257. LZWReadByte (gif_source_ptr sinfo)
  258. /* Read an LZW-compressed byte */
  259. {
  260.   register int code;        /* current working code */
  261.   int incode;            /* saves actual input code */
  262.  
  263.   /* First time, just eat the expected Clear code(s) and return next code, */
  264.   /* which is expected to be a raw byte. */
  265.   if (sinfo->first_time) {
  266.     sinfo->first_time = FALSE;
  267.     code = sinfo->clear_code;    /* enables sharing code with Clear case */
  268.   } else {
  269.  
  270.     /* If any codes are stacked from a previously read symbol, return them */
  271.     if (sinfo->sp > sinfo->symbol_stack)
  272.       return (int) *(-- sinfo->sp);
  273.  
  274.     /* Time to read a new symbol */
  275.     code = GetCode(sinfo);
  276.  
  277.   }
  278.  
  279.   if (code == sinfo->clear_code) {
  280.     /* Reinit state, swallow any extra Clear codes, and */
  281.     /* return next code, which is expected to be a raw byte. */
  282.     ReInitLZW(sinfo);
  283.     do {
  284.       code = GetCode(sinfo);
  285.     } while (code == sinfo->clear_code);
  286.     if (code > sinfo->clear_code) { /* make sure it is a raw byte */
  287.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  288.       code = 0;            /* use something valid */
  289.     }
  290.     /* make firstcode, oldcode valid! */
  291.     sinfo->firstcode = sinfo->oldcode = code;
  292.     return code;
  293.   }
  294.  
  295.   if (code == sinfo->end_code) {
  296.     /* Skip the rest of the image, unless GetCode already read terminator */
  297.     if (! sinfo->out_of_blocks) {
  298.       SkipDataBlocks(sinfo);
  299.       sinfo->out_of_blocks = TRUE;
  300.     }
  301.     /* Complain that there's not enough data */
  302.     WARNMS(sinfo->cinfo, JWRN_GIF_ENDCODE);
  303.     /* Pad data with 0's */
  304.     return 0;            /* fake something usable */
  305.   }
  306.  
  307.   /* Got normal raw byte or LZW symbol */
  308.   incode = code;        /* save for a moment */
  309.   
  310.   if (code >= sinfo->max_code) { /* special case for not-yet-defined symbol */
  311.     /* code == max_code is OK; anything bigger is bad data */
  312.     if (code > sinfo->max_code) {
  313.       WARNMS(sinfo->cinfo, JWRN_GIF_BADDATA);
  314.       incode = 0;        /* prevent creation of loops in symbol table */
  315.     }
  316.     /* this symbol will be defined as oldcode/firstcode */
  317.     *(sinfo->sp++) = (UINT8) sinfo->firstcode;
  318.     code = sinfo->oldcode;
  319.   }
  320.  
  321.   /* If it's a symbol, expand it into the stack */
  322.   while (code >= sinfo->clear_code) {
  323.     *(sinfo->sp++) = sinfo->symbol_tail[code]; /* tail is a byte value */
  324.     code = sinfo->symbol_head[code]; /* head is another LZW symbol */
  325.   }
  326.   /* At this point code just represents a raw byte */
  327.   sinfo->firstcode = code;    /* save for possible future use */
  328.  
  329.   /* If there's room in table, */
  330.   if ((code = sinfo->max_code) < LZW_TABLE_SIZE) {
  331.     /* Define a new symbol = prev sym + head of this sym's expansion */
  332.     sinfo->symbol_head[code] = sinfo->oldcode;
  333.     sinfo->symbol_tail[code] = (UINT8) sinfo->firstcode;
  334.     sinfo->max_code++;
  335.     /* Is it time to increase code_size? */
  336.     if ((sinfo->max_code >= sinfo->limit_code) &&
  337.     (sinfo->code_size < MAX_LZW_BITS)) {
  338.       sinfo->code_size++;
  339.       sinfo->limit_code <<= 1;    /* keep equal to 2^code_size */
  340.     }
  341.   }
  342.   
  343.   sinfo->oldcode = incode;    /* save last input symbol for future use */
  344.   return sinfo->firstcode;    /* return first byte of symbol's expansion */
  345. }
  346.  
  347.  
  348. LOCAL void
  349. ReadColorMap (gif_source_ptr sinfo, int cmaplen, JSAMPARRAY cmap)
  350. /* Read a GIF colormap */
  351. {
  352.   int i;
  353.  
  354.   for (i = 0; i < cmaplen; i++) {
  355.     cmap[CM_RED][i]   = (JSAMPLE) ReadByte(sinfo);
  356.     cmap[CM_GREEN][i] = (JSAMPLE) ReadByte(sinfo);
  357.     cmap[CM_BLUE][i]  = (JSAMPLE) ReadByte(sinfo);
  358.   }
  359. }
  360.  
  361.  
  362. LOCAL void
  363. DoExtension (gif_source_ptr sinfo)
  364. /* Process an extension block */
  365. /* Currently we ignore 'em all */
  366. {
  367.   int extlabel;
  368.  
  369.   /* Read extension label byte */
  370.   extlabel = ReadByte(sinfo);
  371.   TRACEMS1(sinfo->cinfo, 1, JTRC_GIF_EXTENSION, extlabel);
  372.   /* Skip the data block(s) associated with the extension */
  373.   SkipDataBlocks(sinfo);
  374. }
  375.  
  376.  
  377. /*
  378.  * Read the file header; return image size and component count.
  379.  */
  380.  
  381. METHODDEF void
  382. start_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  383. {
  384.   gif_source_ptr source = (gif_source_ptr) sinfo;
  385.   char hdrbuf[10];        /* workspace for reading control blocks */
  386.   unsigned int width, height;    /* image dimensions */
  387.   int colormaplen, aspectRatio;
  388.   int c;
  389.  
  390.   /* Allocate space to store the colormap */
  391.   source->colormap = (*cinfo->mem->alloc_sarray)
  392.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  393.      (JDIMENSION) MAXCOLORMAPSIZE, (JDIMENSION) NUMCOLORS);
  394.  
  395.   /* Read and verify GIF Header */
  396.   if (! ReadOK(source->pub.input_file, hdrbuf, 6))
  397.     ERREXIT(cinfo, JERR_GIF_NOT);
  398.   if (hdrbuf[0] != 'G' || hdrbuf[1] != 'I' || hdrbuf[2] != 'F')
  399.     ERREXIT(cinfo, JERR_GIF_NOT);
  400.   /* Check for expected version numbers.
  401.    * If unknown version, give warning and try to process anyway;
  402.    * this is per recommendation in GIF89a standard.
  403.    */
  404.   if ((hdrbuf[3] != '8' || hdrbuf[4] != '7' || hdrbuf[5] != 'a') &&
  405.       (hdrbuf[3] != '8' || hdrbuf[4] != '9' || hdrbuf[5] != 'a'))
  406.     TRACEMS3(cinfo, 1, JTRC_GIF_BADVERSION, hdrbuf[3], hdrbuf[4], hdrbuf[5]);
  407.  
  408.   /* Read and decipher Logical Screen Descriptor */
  409.   if (! ReadOK(source->pub.input_file, hdrbuf, 7))
  410.     ERREXIT(cinfo, JERR_INPUT_EOF);
  411.   width = LM_to_uint(hdrbuf[0],hdrbuf[1]);
  412.   height = LM_to_uint(hdrbuf[2],hdrbuf[3]);
  413.   colormaplen = 2 << (hdrbuf[4] & 0x07);
  414.   /* we ignore the color resolution, sort flag, and background color index */
  415.   aspectRatio = hdrbuf[6] & 0xFF;
  416.   if (aspectRatio != 0 && aspectRatio != 49)
  417.     TRACEMS(cinfo, 1, JTRC_GIF_NONSQUARE);
  418.  
  419.   /* Read global colormap if header indicates it is present */
  420.   if (BitSet(hdrbuf[4], COLORMAPFLAG))
  421.     ReadColorMap(source, colormaplen, source->colormap);
  422.  
  423.   /* Scan until we reach start of desired image.
  424.    * We don't currently support skipping images, but could add it easily.
  425.    */
  426.   for (;;) {
  427.     c = ReadByte(source);
  428.  
  429.     if (c == ';')        /* GIF terminator?? */
  430.       ERREXIT(cinfo, JERR_GIF_IMAGENOTFOUND);
  431.  
  432.     if (c == '!') {        /* Extension */
  433.       DoExtension(source);
  434.       continue;
  435.     }
  436.     
  437.     if (c != ',') {        /* Not an image separator? */
  438.       WARNMS1(cinfo, JWRN_GIF_CHAR, c);
  439.       continue;
  440.     }
  441.  
  442.     /* Read and decipher Local Image Descriptor */
  443.     if (! ReadOK(source->pub.input_file, hdrbuf, 9))
  444.       ERREXIT(cinfo, JERR_INPUT_EOF);
  445.     /* we ignore top/left position info, also sort flag */
  446.     width = LM_to_uint(hdrbuf[4],hdrbuf[5]);
  447.     height = LM_to_uint(hdrbuf[6],hdrbuf[7]);
  448.     source->is_interlaced = BitSet(hdrbuf[8], INTERLACE);
  449.  
  450.     /* Read local colormap if header indicates it is present */
  451.     /* Note: if we wanted to support skipping images, */
  452.     /* we'd need to skip rather than read colormap for ignored images */
  453.     if (BitSet(hdrbuf[8], COLORMAPFLAG)) {
  454.       colormaplen = 2 << (hdrbuf[8] & 0x07);
  455.       ReadColorMap(source, colormaplen, source->colormap);
  456.     }
  457.  
  458.     source->input_code_size = ReadByte(source); /* get min-code-size byte */
  459.     if (source->input_code_size < 2 || source->input_code_size >= MAX_LZW_BITS)
  460.       ERREXIT1(cinfo, JERR_GIF_CODESIZE, source->input_code_size);
  461.  
  462.     /* Reached desired image, so break out of loop */
  463.     /* If we wanted to skip this image, */
  464.     /* we'd call SkipDataBlocks and then continue the loop */
  465.     break;
  466.   }
  467.  
  468.   /* Prepare to read selected image: first initialize LZW decompressor */
  469.   source->symbol_head = (UINT16 FAR *)
  470.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  471.                 LZW_TABLE_SIZE * SIZEOF(UINT16));
  472.   source->symbol_tail = (UINT8 FAR *)
  473.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  474.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  475.   source->symbol_stack = (UINT8 FAR *)
  476.     (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  477.                 LZW_TABLE_SIZE * SIZEOF(UINT8));
  478.   InitLZWCode(source);
  479.  
  480.   /*
  481.    * If image is interlaced, we read it into a full-size sample array,
  482.    * decompressing as we go; then get_interlaced_row selects rows from the
  483.    * sample array in the proper order.
  484.    */
  485.   if (source->is_interlaced) {
  486.     /* We request the virtual array now, but can't access it until virtual
  487.      * arrays have been allocated.  Hence, the actual work of reading the
  488.      * image is postponed until the first call to get_pixel_rows.
  489.      */
  490.     source->interlaced_image = (*cinfo->mem->request_virt_sarray)
  491.       ((j_common_ptr) cinfo, JPOOL_IMAGE,
  492.        (JDIMENSION) width, (JDIMENSION) height, (JDIMENSION) 1);
  493.     if (cinfo->progress != NULL) {
  494.       cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  495.       progress->total_extra_passes++; /* count file input as separate pass */
  496.     }
  497.     source->pub.get_pixel_rows = load_interlaced_image;
  498.   } else {
  499.     source->pub.get_pixel_rows = get_pixel_rows;
  500.   }
  501.  
  502.   /* Create compressor input buffer. */
  503.   source->pub.buffer = (*cinfo->mem->alloc_sarray)
  504.     ((j_common_ptr) cinfo, JPOOL_IMAGE,
  505.      (JDIMENSION) width * NUMCOLORS, (JDIMENSION) 1);
  506.   source->pub.buffer_height = 1;
  507.  
  508.   /* Return info about the image. */
  509.   cinfo->in_color_space = JCS_RGB;
  510.   cinfo->input_components = NUMCOLORS;
  511.   cinfo->data_precision = 8;
  512.   cinfo->image_width = width;
  513.   cinfo->image_height = height;
  514.  
  515.   TRACEMS3(cinfo, 1, JTRC_GIF, width, height, colormaplen);
  516. }
  517.  
  518.  
  519. /*
  520.  * Read one row of pixels.
  521.  * This version is used for noninterlaced GIF images:
  522.  * we read directly from the GIF file.
  523.  */
  524.  
  525. METHODDEF JDIMENSION
  526. get_pixel_rows (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  527. {
  528.   gif_source_ptr source = (gif_source_ptr) sinfo;
  529.   register int c;
  530.   register JSAMPROW ptr;
  531.   register JDIMENSION col;
  532.   register JSAMPARRAY colormap = source->colormap;
  533.   
  534.   ptr = source->pub.buffer[0];
  535.   for (col = cinfo->image_width; col > 0; col--) {
  536.     c = LZWReadByte(source);
  537.     *ptr++ = colormap[CM_RED][c];
  538.     *ptr++ = colormap[CM_GREEN][c];
  539.     *ptr++ = colormap[CM_BLUE][c];
  540.   }
  541.   return 1;
  542. }
  543.  
  544.  
  545. /*
  546.  * Read one row of pixels.
  547.  * This version is used for the first call on get_pixel_rows when
  548.  * reading an interlaced GIF file: we read the whole image into memory.
  549.  */
  550.  
  551. METHODDEF JDIMENSION
  552. load_interlaced_image (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  553. {
  554.   gif_source_ptr source = (gif_source_ptr) sinfo;
  555.   JSAMPARRAY image_ptr;
  556.   register JSAMPROW sptr;
  557.   register JDIMENSION col;
  558.   JDIMENSION row;
  559.   cd_progress_ptr progress = (cd_progress_ptr) cinfo->progress;
  560.  
  561.   /* Read the interlaced image into the virtual array we've created. */
  562.   for (row = 0; row < cinfo->image_height; row++) {
  563.     if (progress != NULL) {
  564.       progress->pub.pass_counter = (long) row;
  565.       progress->pub.pass_limit = (long) cinfo->image_height;
  566.       (*progress->pub.progress_monitor) ((j_common_ptr) cinfo);
  567.     }
  568.     image_ptr = (*cinfo->mem->access_virt_sarray)
  569.       ((j_common_ptr) cinfo, source->interlaced_image, row, TRUE);
  570.     sptr = image_ptr[0];
  571.     for (col = cinfo->image_width; col > 0; col--) {
  572.       *sptr++ = (JSAMPLE) LZWReadByte(source);
  573.     }
  574.   }
  575.   if (progress != NULL)
  576.     progress->completed_extra_passes++;
  577.  
  578.   /* Replace method pointer so subsequent calls don't come here. */
  579.   source->pub.get_pixel_rows = get_interlaced_row;
  580.   /* Initialize for get_interlaced_row, and perform first call on it. */
  581.   source->cur_row_number = 0;
  582.   source->pass2_offset = (cinfo->image_height + 7) / 8;
  583.   source->pass3_offset = source->pass2_offset + (cinfo->image_height + 3) / 8;
  584.   source->pass4_offset = source->pass3_offset + (cinfo->image_height + 1) / 4;
  585.  
  586.   return get_interlaced_row(cinfo, sinfo);
  587. }
  588.  
  589.  
  590. /*
  591.  * Read one row of pixels.
  592.  * This version is used for interlaced GIF images:
  593.  * we read from the virtual array.
  594.  */
  595.  
  596. METHODDEF JDIMENSION
  597. get_interlaced_row (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  598. {
  599.   gif_source_ptr source = (gif_source_ptr) sinfo;
  600.   JSAMPARRAY image_ptr;
  601.   register int c;
  602.   register JSAMPROW sptr, ptr;
  603.   register JDIMENSION col;
  604.   register JSAMPARRAY colormap = source->colormap;
  605.   JDIMENSION irow;
  606.  
  607.   /* Figure out which row of interlaced image is needed, and access it. */
  608.   switch ((int) (source->cur_row_number & 7)) {
  609.   case 0:            /* first-pass row */
  610.     irow = source->cur_row_number >> 3;
  611.     break;
  612.   case 4:            /* second-pass row */
  613.     irow = (source->cur_row_number >> 3) + source->pass2_offset;
  614.     break;
  615.   case 2:            /* third-pass row */
  616.   case 6:
  617.     irow = (source->cur_row_number >> 2) + source->pass3_offset;
  618.     break;
  619.   default:            /* fourth-pass row */
  620.     irow = (source->cur_row_number >> 1) + source->pass4_offset;
  621.     break;
  622.   }
  623.   image_ptr = (*cinfo->mem->access_virt_sarray)
  624.     ((j_common_ptr) cinfo, source->interlaced_image, irow, FALSE);
  625.   /* Scan the row, expand colormap, and output */
  626.   sptr = image_ptr[0];
  627.   ptr = source->pub.buffer[0];
  628.   for (col = cinfo->image_width; col > 0; col--) {
  629.     c = GETJSAMPLE(*sptr++);
  630.     *ptr++ = colormap[CM_RED][c];
  631.     *ptr++ = colormap[CM_GREEN][c];
  632.     *ptr++ = colormap[CM_BLUE][c];
  633.   }
  634.   source->cur_row_number++;    /* for next time */
  635.   return 1;
  636. }
  637.  
  638.  
  639. /*
  640.  * Finish up at the end of the file.
  641.  */
  642.  
  643. METHODDEF void
  644. finish_input_gif (j_compress_ptr cinfo, cjpeg_source_ptr sinfo)
  645. {
  646.   /* no work */
  647. }
  648.  
  649.  
  650. /*
  651.  * The module selection routine for GIF format input.
  652.  */
  653.  
  654. GLOBAL cjpeg_source_ptr
  655. jinit_read_gif (j_compress_ptr cinfo)
  656. {
  657.   gif_source_ptr source;
  658.  
  659.   /* Create module interface object */
  660.   source = (gif_source_ptr)
  661.       (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  662.                   SIZEOF(gif_source_struct));
  663.   source->cinfo = cinfo;    /* make back link for subroutines */
  664.   /* Fill in method ptrs, except get_pixel_rows which start_input sets */
  665.   source->pub.start_input = start_input_gif;
  666.   source->pub.finish_input = finish_input_gif;
  667.  
  668.   return (cjpeg_source_ptr) source;
  669. }
  670.  
  671. #endif /* GIF_SUPPORTED */
  672.